<?php
namespace app\api\controller;
use think\Log;
use think\Db;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Ecs\Ecs;

class Sms extends Basic
{
	static $acsClient = null;
    public  function randomstring($length = 8) {
        $str = 'abcdefghijkmnopqrstuvwxyz0123456789';
        for ($i = 0, $passwd = ''; $i < $length; $i++)
            $passwd .= substr($str, mt_rand(0, strlen($str) - 1), 1);

        return $passwd;
    }

    // 获取最近5s订单
    public function getOrders()
    {
        // $res = $this->sendSms('13347890121','SMS_173471929',['pro'=>'111','code'=>'222']);
        // var_dump($res);die();
        $token = $this->getToken();
        $start_time = time()-1000;
        $end_time = time();

        $res = $this->getOrderList('all',date('Y-m-d H:i:s',$start_time),date('Y-m-d H:i:s',$end_time));
        if($res = json_decode($res,true)) {
            // var_dump($res);exit;
            $orders = $res['result']['orders'];
            if($orders) {
                foreach ($orders as $key => $value) {
                    // var_dump($value['status']);exit;
                    $order_id = $value['order_id'];
                    if($value['status']<20 || Db('wdcode')->where(['order_id'=>$order_id])->find()) {
                        continue;
                    }
                    // 获取订单详情
                    $orderinfores = $this->getOrderDetails($order_id);
                    if($orderinfores = json_decode($orderinfores,true)) {
                        
                        $order = $orderinfores['result'];
                        $arr['phone'] = $order['buyer_info']['phone'];
                        $items = $order['items'];
                        $arr['title'] = '';
                        $data = [];
                        if($items) {
                            foreach ($items as $key => $value) {
                                preg_match_all('/\#.+\#/', $value['item_name'], $titlearr);
                                if(isset($titlearr[0][0])) {
                                	if(strstr($titlearr[0][0], '会员')) {
                                		$name = '会员';
                                		$id = 0;
                                	} else {
                                		list($name,$id) = explode('_', trim($titlearr[0][0],'#'));
                                	}
                                    
                                } else {
                                    echo json_encode(['status'=>'success']);
                                    return ;
                                }
                                $data[] = [
                                    'num'=>$value['quantity'],
                                    'name'=>isset($name)&&$name?$name:'',
                                    'id'=>isset($id)&&$id?$id:'',
                                ];
                                $arr['title'] = $arr['title'].$value['item_name'].' ';
                            }
                        }
                        $arr['data'] = json_encode($data);
                        $arr['order_id'] = $order_id;
                        $arr['code'] = $this->randomstring();
                        $arr['create_time'] = $arr['update_time'] = time();
                        // var_dump($arr);exit;
                        Db('wdcode')->insert($arr);
                        $this->sendSms($arr['phone'],'SMS_173471929',['pro'=>$arr['title'],'code'=>$arr['code']]);
                    }
                }
            }
        }
    }

    public function qf()
    {
//         foreach ([['p'=>'15805697395','c'=>'4ocxo90r'],
// ['p'=>'18839895698','c'=>'3f5nygro'],
// ['p'=>'17610603118','c'=>'vpswk27e'],
// ['p'=>'17878692616','c'=>'e69nxdqc'],
// ['p'=>'13627366837','c'=>'nmier6x7'],
// ['p'=>'13719688663','c'=>'mzv92wsq'],
// ['p'=>'18897554275','c'=>'vq5y4s0p'],
// ['p'=>'17506176533','c'=>'n417vbmd'],
// ['p'=>'15238471169','c'=>'tt7djif4'],
// ['p'=>'13558821867','c'=>'nnm9t4cb'],
// ['p'=>'15169115638','c'=>'34j2dc7s'],
// ['p'=>'18132703229','c'=>'xpkd3nud'],
// ['p'=>'13805861850','c'=>'rv6jqusk'],
// ['p'=>'18573174747','c'=>'8k3mdmbo'],
// ['p'=>'13283806502','c'=>'z1ucta1b'],
// ['p'=>'13963790837','c'=>'gz11su2y'],] as $key => $value) {
//             $this->sendSms($value['p'],'SMS_173471929',['pro'=>'小程序一年会员','code'=>$value['c']]);
//         }
    }

    public function getOrderList($order_type, $add_start, $add_end) {
        return NetUtils::getInstance ()->post ( "https://api.vdian.com/api", array (
                "param" => '{"page_num":' . '1' . ',"page_size":30,"order_type":"' . $order_type . '","update_start":"' . $add_start . '","update_end":"' . $add_end . '"}',
                "public" => $this->buildPublicValue( "vdian.order.list.get" ,'1.2') 
        ) );
    }
    public function buildPublicValue($method, $version = "1.0", $format = "json") {
        return '{"method":"' . $method . '","access_token":"' . $this->getToken() . '","version":"'.$version.'","format":"' . $format . '","lang":"php"}';
    }

    public function getToken()
    {
        $access_token_obj = Db('site')->where(['name'=>'微店access_token'])->find();
        // token没过期
        if($access_token_obj && $access_token_obj['url']>time()) {
            return $access_token_obj['value'];
        }
        $refresh_token_obj = Db('site')->where(['name'=>'微店refresh_token'])->find();
        // https://oauth.open.weidian.com/oauth2/refresh_token?appkey=xxx&grant_type=refresh_token&refresh_token=xxx    
        $res = $this->curl_request("https://oauth.open.weidian.com/oauth2/refresh_token?appkey=690934&grant_type=refresh_token&refresh_token=".$refresh_token_obj['value']);
        if($res = json_decode($res,true)) {
            $access_token = $res['result']['access_token'];
            Db('site')->where(['name'=>'微店access_token'])->update(['value'=>$access_token,'url'=>time()+86000]);
            return $access_token;
        }
    }

    public function getDetail($order_id='811438341574370')
    {
        var_dump($this->getOrderDetails($order_id));exit;
    }

    public function getOrderDetails($order_id) {
        return NetUtils::getInstance ()->post ( "https://api.vdian.com/api", array (
                "param" => '{"order_id":"' . $order_id . '"}',
                "public" => $this->buildPublicValue ( "vdian.order.get" ,'1.0') 
        ) );
    }


    /**
     * 发送短信
     * @return stdClass
     */
    public function sendSms($phone='',$tem='SMS_173471929',$arr=[]) {
		// 设置全局客户端
		AlibabaCloud::accessKeyClient('LTAINiJ0Newhjmeb', 'Zgcmohu3eXAUo7Mq5VwRA3h3Jh7fpx')
		            ->regionId('cn-hangzhou')
		            ->asDefaultClient();
        try {
		    $result = AlibabaCloud::rpc()
		                          ->product('Dysmsapi')
		                          // ->scheme('https') // https | http
		                          ->version('2017-05-25')
		                          ->action('SendSms')
		                          ->method('POST')
		                          ->host('dysmsapi.aliyuncs.com')
		                          ->options([
		                                        'query' => [
		                                          'RegionId' => "cn-hangzhou",
		                                          'PhoneNumbers' => $phone,
		                                          'SignName' => "环球人物",
		                                          'TemplateCode' => $tem,
		                                          'TemplateParam' => json_encode($arr),
		                                        ],
		                                    ])
		                          ->request();
		    print_r($result->toArray());
		} catch (ClientException $e) {
		    echo $e->getErrorMessage() . PHP_EOL;
		} catch (ServerException $e) {
		    echo $e->getErrorMessage() . PHP_EOL;
		}

    }

    public function checkcode($code='',$user_id='')
    {
    	$user_id = decode($user_id);
    	$user = Db('user')->where(['id'=>$user_id])->find();
    	// Log::write($user_id,'notice');
    	// $user = Db('user')->where(['id'=>40427])->find();
    	// var_dump($user);exit;
    	$codeobj = Db('wdcode')->where(['code'=>$code,'is_use'=>0])->find();
    	if($user && $codeobj) {
    		$data = json_decode($codeobj['data'],true);
    		if($data) {
    			$txt = '您已成功兑换 ';
    			foreach ($data as $key => $value) {
    				// var_dump($value);exit;
    				// 如果是会员
    				if($value['name']=='会员') {
    					$addtime = 86400*365*$value['num'];
    					$vip_start_time = $user['vip_start_time']?$user['vip_start_time']:time();
    					$vip_end_time = $user['vip_end_time']>time()?($user['vip_end_time']+$addtime):(time()+$addtime);
    					Db('user')->where(['id'=>$user_id])->update(['is_vip'=>1,'vip_end_time'=>$vip_end_time,'vip_start_time'=>$vip_start_time]);
    					$txt = $txt.$value['num'].'年会员 ';
    				} elseif($value['name']=='电子刊') {
    					$this->add_ebookcode($value['num'],$value['id'],$user['id']);
    					$txt = $txt.$value['num'].'份'.$value['name'].' ';
    				} else {
    					$arr['user_id'] = $user['id'];
    					$arr['type'] = $value['name']=='杂志'?2:3;
    					$arr['pid'] = $value['id'];
    					$arr['is_forever'] = $arr['status'] = 1;
    					$arr['create_time'] = time();
    					Db('user_subscribe')->insert($arr);
    					$txt = $txt.$value['num'].'份'.$value['name'].' ';
    				}
    			}
    			Db('wdcode')->where(['code'=>$code])->update(['is_use'=>1,'update_time'=>time()]);
    			$codeobj['phone'] && Db('user')->where(['id'=>$user['id']])->update(['mobile'=>$codeobj['phone']]);
    			json_success($txt);
    		}
    		
    	} else {
    		json_success('兑换失败');
    	}
    }

    public function add_ebookcode($num=1,$eid=0,$uid=0)
    {
        for ($i=0; $i < $num; $i++) { 
            $map = [
                'uid'=>$uid,
                'code'=>$this->getRandomString(10),
                'eid'=>$eid,
                'status'=>1
            ];
            $EbookCode = new \app\api\model\EbookCode();
            $EbookCode->allowField(true)->save($map);
        }
    }

     public function getRandomString($len, $chars=null)  
    {  
        if (is_null($chars)) {  
            $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
        }  
        mt_srand(10000000*(double)microtime());  
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
            $str .= $chars[mt_rand(0, $lc)];  
        }  
        return $str;  
    } 

    public function donum($num='1')
    {
    	$all = [];
    	for ($i=1; $i <= $num; $i++) { 
    		$data = [[
                'num'=>1,
                'name'=>'会员',
                'id'=>0,
            ]];
    		$arr['data'] = json_encode($data);
            $arr['order_id'] = 'xlb_'.$i;
            $arr['code'] = $this->randomstring();
            $arr['status'] = 1;
            $arr['title'] = '小裂变兑换会员';
            $arr['create_time'] = $arr['update_time'] = time();
            $all[] =  $arr['code'];
            // var_dump($arr);exit;
            Db('wdcode')->insert($arr);
    	}
    	var_dump(implode(',', $all));exit;
    }
}